<?php
namespace app\houtai\controller\user\union;
use app\houtai\controller\BaseController;
use think\db\Expression;
use think\Db;
use think\Request;
use org\GoApi\FamilyCtrl;

class IndexController extends BaseController {
    /**
     *  @brief  : 大联盟绑定查询
     *  @return : page|JSON
     *  @details:
     */
    public function indexAction() {
        $conds = ['a.Status' => 1, 'b.State' => 1];
        $order = [];
        $GAME_KIND  = GetGameKind();
        $CHANNELS   = $this->GetAdminChannel();
        ////////////////////////////////////////////////////////////////////////////
        $channel = $this->request->param('channel/d', -1);
        if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
            $conds['c.Channel'][] = ['IN', array_keys($CHANNELS)];
            $conds['c.Channel'][] = ['EQ', $channel];
        } else {
            $conds['c.Channel'] = ['IN', array_keys($CHANNELS)];
        }
        //////////////////////////////////////////////////////
        $kind = $this->request->param('kind/d', -1);
        if ($kind > 0 && array_key_exists($kind, $GAME_KIND)) {
            $conds['b.KindID'] = $kind;
        }
        //////////////////////////////////////////////////////

        $black = $this->request->param('black/d', -1); // 是否在黑名单
        if ($black >= 0 && in_array($black, [0, 1])) {
            $conds['a.IsBlack'] = $black;
        }

        //////////////////////////////////////////////////////
        $search = $this->request->param('search/s', '', 'trim');
        if (!empty($search)) {
            if (is_numeric($search)) {
                $search = $this->request->param('search/d', 0);
                $conds['a.MemberUID|c.GameID'] = $search;
            } else {
                $conds['c.NickName'] = ['LIKE', "%{$search}%"];
            }
        }
        //////////////////////////////////////////////////////
        $code1 = $this->request->param('code1/d', 0);
        if ($code1 > 0) {
            $conds['b.Code'] = $code1;  // 六位群号
        }
        $code2 = $this->request->param('code2/d', 0); // 所属推广员邀请码
        if ($code2 > 0) {
            $conds['g.GameID'] = $code2;
        }
        $code3 = $this->request->param('code3/d', 0); // 群主GameID
        if ($code3 > 0) {
            $conds['e.GameID'] = $code3;
        }
        $code4 = $this->request->param('code4/d', 0); // 群号
        if ($code4 > 0) {
            $conds['b.Code'] = $code4;
        }
        //////////////////////////////////////////////////////
        $orderMap = [
            'A' => 'ID',
            'B' => 'Channel',
            'C' => 'KindID',
            'D' => 'Code',
            'E' => 'GameID',
            'F' => 'AGameID',
            'G' => 'FGameID',
            'H' => 'CreateTime',
            'I' => 'UpdateTime',
        ];
        $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'G';
        $order[$orderMap[$this->orderField]] = $this->orderDirection;
        $codes['a.Code'] = $code1;
        ////////////////////////////////////////////////////////////////////////////
        $list = table('CYWebSMSDB.dbo.UnionMember a', 'rydb.websms')->field([
            'a.ID', 'a.MemberUID' => 'UserID', 'a.UserRight', 'a.IsBlack', 'a.IsPass',
            'a.CreateTime', 'a.UpdateTime', 'a.UserRight', 'b.AUID' => 'FUserID', 'a.Gold',
            'b.Code', 'b.KindID', 'c.GameID', 'c.NickName', 'c.Sex','b.FamilyType',
            'c.AccountsType', 'c.Channel', "ISNULL(c.AccountImgUrl, '')" => 'Avatar',
            'c.Accounts', 'c.Compellation', 'c.PassPortID', 'c.RegisterMobile', 'c.RegisterDate',
            'c.RegisterIP', 'c.GameLogonCount', 'c.LastLogonDate', 'c.LastLogonIP',
            'e.GameID' => 'FGameID', 'e.AccountsType' => 'FAccountsType',
            '(CASE WHEN LEN([e].[Compellation]) = 0 THEN [e].[NickName] ELSE [e].[Compellation] END)'=>'FCompellation',
            'ISNULL(e.SpreaderID, 0)' => 'AUserID', 'ISNULL(g.GameID, 0)' => 'AGameID',
            "ISNULL(g.Compellation, '')" => 'ACompellation', "ISNULL(g.AccountImgUrl, '')" => 'AAvatar',
            'ISNULL(g.AccountsType, 0)' => 'AAccountsType', "ISNULL(e.AccountImgUrl, '')" => 'FAvatar',
            '(CASE WHEN a.MemberUID = b.AUID THEN 1 ELSE 0 END)' => 'IsBoss',
        ])
            ->join('CYWebSMSDB.dbo.Family b', 'b.ID = a.FamilyID', 'LEFT')
            // 成员
            ->join('CYBasicDB.dbo.AccountsInfo c', 'c.UserID = a.MemberUID', 'LEFT')
            // 群主
            ->join('CYBasicDB.dbo.AccountsInfo e', 'e.UserID = b.AUID AND e.Channel = c.Channel', 'LEFT')
            //
            ->join('CYBasicDB.dbo.ChannelConfig k', 'k.ID = c.Channel', 'LEFT')
            ->join('CYBasicDB.dbo.AccountsGameCurrency f', 'f.UserID = a.MemberUID', 'LEFT')
            // 代理
            ->join('CYBasicDB.dbo.AccountsInfo g', 'g.UserID = c.SpreaderID', 'LEFT')
            ->where($conds)->order($order)->paginate();
        ////////////////////////////////////////////////////////////////////////////
        return $this->fetch('', [
            'CHANNELS'  => $CHANNELS,
            'channel'   => $channel,
            'GAME_KIND' => $GAME_KIND,
            'kind'    => $kind,
            'code1'   => $code1 === 0 ? -1 : $code1,
            'code2'   => $code2 === 0 ? '' : $code2,
            'code3'   => $code3 === 0 ? '' : $code3,
            'list'    => $list,
            'search'  => $search,
            'black'   => $black,
        ]);
    }






    /**
   *  @brief : 大联盟规则管理
   *  @return: page
   *  @detail: 
   */
  public function ruleAction() {
  
    $order = [];
    $GAME_KIND  = GetGameKind();
    $CHANNELS   = $this->GetAdminChannel();
    ////////////////////////////////////////////////////////////////////////////
    $channel = $this->request->param('channel/d', -1);
    if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
      $conds['a.Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['a.Channel'][] = ['EQ', $channel];
    } else {
      $conds['a.Channel'] = ['IN', array_keys($CHANNELS)];
    }
    //////////////////////////////////////////////////////
    $kind = $this->request->param('kind/d', -1);
    if ($kind > 0 && array_key_exists($kind, $GAME_KIND)) {
      $conds['a.KindID'] = $kind;
    }
    //////////////////////////////////////////////////////

    $paytype = $this->request->param('Paytype/d', -1); // 支付方式
    if ($paytype >= 0 && in_array($paytype, [1, 2])) {
      $conds['a.PayType'] = $paytype;
    }

    //////////////////////////////////////////////////////
    $search = $this->request->param('search/s', '', 'trim');
    if (!empty($search)) {
      if (is_numeric($search)) {
        $search = $this->request->param('search/d', 0);
        $conds['a.UserID|c.GameID'] = $search;
      } else {
        $conds['c.NickName'] = ['LIKE', "%{$search}%"];
      }
    }
    //////////////////////////////////////////////////////
    $code1 = $this->request->param('code1/d', 0);
    if ($code1 > 0) {
      $conds['a.GroupID'] = $code1;  // 六位群号
    }
    $code3 = $this->request->param('code3/d', 0); // 群主GameID
    if ($code3 > 0) {
      $conds['e.GameID'] = $code3;
    }
      $code4 = $this->request->param('code4/d', 0); // 群号
      if ($code4 > 0) {
          $conds['a.GroupID'] = $code4;
      }
    //////////////////////////////////////////////////////
    $orderMap = [
      'A' => 'ID',
      'B' => 'Channel',
      'C' => 'KindID',
      'D' => 'GroupID',
      'E' => 'GameID',
      'F' => 'FGameID',
      'H' => 'EnterTableGold',
      'I' => 'ExitTableGold',
      'J' => 'CreateTime',
      
    ];
    $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'J';
    $order[$orderMap[$this->orderField]] = $this->orderDirection;
    $codes['a.Code'] = $code1;
    $list = table('CYRecordDB.dbo.RecordUnionGameRule a', 'rydb.record')->field([
      'a.*', 'd.UserRight', 'd.IsBlack', 'd.IsPass',
      'b.AUID' => 'FUserID', 
      'b.Code', 'c.GameID', 'c.NickName', 'c.Sex','b.FamilyType',
      'c.AccountsType', "ISNULL(c.AccountImgUrl, '')" => 'Avatar',
      'c.Accounts', 'c.Compellation', 'c.PassPortID', 'c.RegisterMobile', 'c.RegisterDate',
      'c.RegisterIP', 'c.GameLogonCount', 'c.LastLogonDate', 'c.LastLogonIP',
      'e.GameID' => 'FGameID', 'e.AccountsType' => 'FAccountsType',
      '(CASE WHEN LEN([e].[Compellation]) = 0 THEN [e].[NickName] ELSE [e].[Compellation] END)'=>'FCompellation',
      'ISNULL(e.SpreaderID, 0)' => 'AUserID', 
      '(CASE WHEN a.UserID = b.AUID THEN 1 ELSE 0 END)' => 'IsBoss',
    ])
    //群信息
    ->join('CYWebSMSDB.dbo.Family b', 'b.Code = a.GroupID', 'LEFT')
    // 成员
    ->join('CYBasicDB.dbo.AccountsInfo c', 'c.UserID = a.UserID', 'LEFT')
    //属性
    ->join('CYWebSMSDB.dbo.FamilyMember d', 'd.MemberUID = a.UserID', 'LEFT')
    // 群主
    ->join('CYBasicDB.dbo.AccountsInfo e', 'e.UserID = a.UserID AND e.Channel = a.Channel', 'LEFT')
    //渠道信息
    ->join('CYBasicDB.dbo.ChannelConfig k', 'k.ID = c.Channel', 'LEFT')
    //附属信息
    ->join('CYBasicDB.dbo.AccountsGameCurrency f', 'f.UserID = a.UserID', 'LEFT')
    ->where($conds)->order($order)->paginate()->each(function( $item, $key){
      $item['RuleData'] = json_decode($item['RuleData'],true);
      return $item;
      });
    // echo "<pre/>";
    // print_r($list);die;
    
    ////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'CHANNELS'  => $CHANNELS,
      'channel'   => $channel,
      'GAME_KIND' => $GAME_KIND,
      'kind'    => $kind,
      'code1'   => $code1 === 0 ? -1 : $code1,
      'code3'   => $code3 === 0 ? '' : $code3,
      'list'    => $list,
      'search'  => $search,
      'PayType'   => $paytype,
    ]);

  }

   /**
   *  @brief  : 大联盟群组管理
   *  @return : page
   *  @details: 
   */
  public function familyAction() {

    $order = [];
    $STATES   = [0 => '待审核', 1 => '已审核', 2 => '已退回'];
    $GAME_KIND  = GetGameKind();
    $FAMILYTYPE = GetFamilyType();
    $CHANNELS   = $this->GetAdminChannel();
    ////////////////////////////////////////////////////////////////////////////
    $channel = $this->request->param('channel/d', -1);
    $familytype = $this->request->param('FamilyType/d', -1);
    if ($familytype > 0){
        $conds['a.FamilyType']  = $familytype;
    }
    $conds['a.FamilyType']  = ['EQ',2];
    if ($channel > 0 && array_key_exists($channel, $CHANNELS)) {
      $conds['b.Channel'][] = ['IN', array_keys($CHANNELS)];
      $conds['b.Channel'][] = ['EQ', $channel];
    } else {
      $conds['b.Channel'] = ['IN', array_keys($CHANNELS)];
    }
    $kind = $this->request->param('kind/d', -1);
    $kind = array_key_exists($kind, $GAME_KIND) ? $kind : -1;
    if ($kind > 0) {
      $conds['a.KindID'] = $kind;
    }
    $state = $this->request->param('state/d', -1);
    $state = array_key_exists($state, $STATES) ? $state : -1;
    if ($state >= 0) {
      $conds['a.State'] = $state;
    }
    //////////////////////////////////////////////////////
    $search = $this->request->param('search/d', 0);
    if ($search > 0) {
      $conds['a.Code|b.GameID|a.AUID'] = $search;
    }
    //////////////////////////////////////////////////////
    $orderMap = [
      'A' => 'ID',
      'B' => 'Channel',
      'C' => 'KindID',
      'D' => 'Code',
      'E' => 'Caption',
      'F' => 'GameID',
      'G' => 'TotalMem',
      'H' => 'TotalBlack',
      'K' => 'State',
      'L' => 'UpdateTime',
    ];
    $this->orderField = array_key_exists($this->orderField, $orderMap) ? $this->orderField : 'L';
    $order[$orderMap[$this->orderField]] = $this->orderDirection;
    //////////////////////////////////////////////////////
    $list = table('CYWebSMSDB.dbo.Family a', 'rydb.websms')->field([
      'a.*', 'b.GameID', 'b.Sex', 'b.AccountsType',
      'c.Total' => 'TotalMem', 'f.Total' => 'TotalBlack', 'b.AccountImgUrl',
      'd.AutoFamily', '(CASE WHEN LEN([b].[Compellation])>0 THEN [b].[Compellation] ELSE [b].[NickName] END )' => 'NickName',
    ])
    ->join('CYBasicDB.dbo.AccountsInfo b', 'b.UserID = a.AUID', 'LEFT')
    ->join('(SELECT FamilyID, COUNT (ID) AS Total FROM CYWebSMSDB.dbo.UnionMember WHERE Status = 1 AND IsBlack = 0 GROUP BY FamilyID) c', 'c.FamilyID = a.ID', 'LEFT')
    ->join('(SELECT FamilyID, COUNT (ID) AS Total FROM CYWebSMSDB.dbo.UnionMember WHERE Status = 1 AND IsBlack = 1 GROUP BY FamilyID) f', 'f.FamilyID = a.ID', 'LEFT')
    ->join('CYWebSMSDB.dbo.AgentReg d', 'd.UserID = a.AUID', 'LEFT')
    ->where($conds)->order($order)->paginate();
    // echo  table('RYWebSMSDB.dbo.Family a', 'rydb.websms')->getLastSql();die;
    ////////////////////////////////////////////////////////////////////////////
    $GroupID = [];
    foreach($list->items() as $item) {
      if ($item['Code'] > 0) {
        $GroupID[] = $item['Code'];
      }
    }
    $RangeScore = [];
    if (!empty($GroupID)) {
      $data = FamilyCtrl::Find($GroupID);
      if (!empty($data['Data'])) {
        $data = $data['Data'];
        foreach($data as & $item) {
          $GroupID = $item['GameID'];
          unset($item['GameID']);
          $RangeScore[$GroupID] = $item;
        }
      }
    }
    ////////////////////////////////////////////////////////////////////////////
    return $this->fetch('', [
      'CHANNELS'  => $CHANNELS,
      'GAME_KIND' => $GAME_KIND,
      'STATES'    => $STATES,
      'channel'   => $channel,
      'FamilyType'=> $FAMILYTYPE,
      'kind'      => $kind,
      'state'     => $state,
      'search'    => $search === 0 ? '' : $search,
      'list'      => $list,
      'RangeScore'=> $RangeScore,
    ]);
  }


    /**
     *  @brief  : 修改信息配置
     *  @return : PAGE|JSON
     *  @details:
     */
    public function detailAction() {

        $id = $this->request->param('id/d', 0);
        $MaxUnion = table('Family', 'rydb.websms')->where(['State' => 1,'FamilyType' =>2])->order("UNWeight desc")->find();

        if ($id > 0) {
            $Union = table('Family', 'rydb.websms')->where(['ID' => $id])->find();

        }
        if ($this->request->isGet()) {

            return $this->fetch('', ['row' => $Union,'MaxUNWeight'=>$MaxUnion['UNWeight']]);
        }
        if ($this->request->isPost()) {
            $Caption = $this->request->param('Caption/s','','trim');
            $UNWeight = $this->request->param('UNWeight/d',0);
            table('Family','rydb.websms')->where(['ID'=>$id])->update(['Caption'=>$Caption,'UNWeight'=>$UNWeight]);
            return result([], 0);
        }
    }

     /**
   *  @brief  : 群审核通过
   *  @return : JSON
   *  @details: 
   */
  public function agreeAction() {
    if (!$this->request->isPost()) {
      return result([], 1, '非法请求');
    }
    $id = $this->request->param('id/d', 0);
    if ($id <= 0) {
      return result([], 2, '业务参数非法');
    }
    $family = table('Family', 'rydb.websms')->where(['ID' => $id])->find();

    if (empty($family)) {
      return result([], 3, '欲处理的数据不存在');
    }
    if ($family['State']==1) {
      return result([], 4, '欲处理的群已审核');
    }
    if ($family['Code'] > 0) {
      return result([], 5, '欲处理的群已分配群号');
    }
    $code = table('CodeIdentifier', 'rydb.websms')->where(['FamilyUsed' => 0])->order('ID')->find();
    if (empty($code)) {
      return result([], 6, '系统分配六位群标识失败');
    }
    $eax = table('Family', 'rydb.websms')->where(['ID' => $family['ID']])->update([
      'Code'  => $code['Code'],
      'State' => 1,
      'UpdateTime'  => new Expression('GETDATE()'),
    ]);
    table('CodeIdentifier', 'rydb.websms')->where(['ID' => $code['ID']])->setField('FamilyUsed', $family['ID']);
    $member = table('UnionMember', 'rydb.websms')->where(['FamilyID' => $family['ID'], 'MemberUID' => $family['AUID']])->find();
    
    $UnionRuleNumb = 5;
    
    if (empty($member)) {
      $eax = table('UnionMember', 'rydb.websms')->insert(['FamilyID' => $family['ID'], 'MemberUID' => $family['AUID'], 'Status' => 1, 'IsPass' => 1,'UnionRuleNumb'=>$UnionRuleNumb,'UserRight'=>64,'FamilyCode'=>$code['Code'],'Gold'=>100000]);
    } else {
      $eax = table('UnionMember', 'rydb.websms')->where(['ID' => $member['ID']])->update(['Status' => 1, 'IsPass' => 1, 'UpdateTime' => new Expression('GETDATE()'),'UnionRuleNumb'=>$UnionRuleNumb,'UserRight'=>64,'FamilyCode'=>$code['Code'],'Gold'=>100000]);
    }
    return result([], 0);
  }
}